import { h, render, shallowReactive } from 'vue'
import type { MessagePropsOmit, MessageInstanceProps } from './types'
import HMessage from './HMessage.vue'
import useZIndex from '../../hooks/useZIndex'

const messageInstance = shallowReactive<MessageInstanceProps[]>([])
let step = 1

export const createMessage = (props: MessagePropsOmit) => {
    const { nextZIndex } = useZIndex()
    const id = `message__${step++}`
    const createDom = document.createElement('div')
    const unRender = () => {
        // 删除数组中的实例
        const instanceNum = messageInstance.findIndex(item => item.id == id)
        if (instanceNum == -1) return
        messageInstance.splice(instanceNum, 1)
        // 销毁组件实例
        render(null, createDom)
    }
    const newProps = {
        ...props,
        destroy: unRender,
        id,
        zIndex: nextZIndex()

    }
    const vnode = h(HMessage, newProps)

    // 创建模版
    render(vnode, createDom)
    // ! 非空断言符
    // 将模版添加到DOM中
    document.body.appendChild(createDom.firstElementChild!)

    const vm = vnode.component!
    // 手动调用删除
    const manualDestroy = () => {
        const instance = messageInstance.find(item => item.id == id)
        if (instance) {
            instance.vm.exposed!.visible.value = false
        }
    }
    const messageInstanceObj = {
        id,
        vnode,
        vm,
        messageProps: newProps,
        destroy: manualDestroy
    }

    // 将当前Message实例添加到数组中
    messageInstance.push(messageInstanceObj)
    return messageInstanceObj
}

export const getLastInstance = () => {
    return messageInstance.at(-1)
}

// 计算上一个实例的最下边的坐标，第一个是0
export const getLastBottonOffset = (id: string) => {
    const indexNum = messageInstance.findIndex(item => item.id == id)
    if (indexNum <= 0) {
        return 0
    } else {
        return messageInstance[indexNum - 1].vm.exposed!.bottomOffset.value
    }
}


// 关闭所有实例
export const closeAll = () => {
    messageInstance.forEach(instance => {
        instance.destroy()
    })
}